package com.k8sops.backend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.k8sops.backend.mapper.DOSProjectGroupMapper;
import com.k8sops.backend.model.entity.DOSProjectGroup;
import com.k8sops.backend.service.DOSProjectGroupService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.Date;

/**
 * Project Group Service Implementation
 */
@Service
public class DOSProjectGroupServiceImpl extends ServiceImpl<DOSProjectGroupMapper, DOSProjectGroup> implements DOSProjectGroupService {

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addProjectGroup(DOSProjectGroup projectGroup) {
        return this.save(projectGroup);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateProjectGroup(DOSProjectGroup projectGroup) {
        projectGroup.setUpdatedAt(LocalDateTime.now());
        return this.updateById(projectGroup);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteProjectGroupById(Long id) {
        // Logical delete
        DOSProjectGroup projectGroup = new DOSProjectGroup();
        projectGroup.setId(id);
        projectGroup.setDeletedAt(LocalDateTime.now());
        projectGroup.setUpdatedAt(LocalDateTime.now());
        return this.updateById(projectGroup);
    }

    @Override
    public DOSProjectGroup getProjectGroupById(Long id) {
        return this.getById(id);
    }

    @Override
    public IPage<DOSProjectGroup> pageProjectGroups(Integer page, Integer size, String groupName) {
        Page<DOSProjectGroup> pageParam = new Page<>(page, size);
        LambdaQueryWrapper<DOSProjectGroup> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.isNull(DOSProjectGroup::getDeletedAt);
        // Add filter conditions
        if (StringUtils.hasText(groupName)) {
            queryWrapper.like(DOSProjectGroup::getName, groupName);
        }
        
        // Sort by create time in descending order
        queryWrapper.orderByDesc(DOSProjectGroup::getCreatedAt);
        
        return this.page(pageParam, queryWrapper);
    }
}
